package Welsy4.Connect.commands
{
	import com.adobe.cairngorm.commands.SequenceCommand;
	import mx.rpc.events.ResultEvent;
	import Welsy4.Connect.business.PrincipalListDelegate;
	import Welsy4.Connect.events.PrincipalListEvent;
	import Welsy4.Connect.events.ChainEvent;
	import Welsy4.Connect.events.ResponseEvent;
	import Welsy4.Connect.model.ConnectModel;
	import Welsy4.Connect.vo.HttpServiceHandler;
	
	import com.adobe.cairngorm.commands.Command;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.cairngorm.control.CairngormEventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.IResponder;

	public class SetCurrentUserIdCommand extends SequenceCommand implements Command, IResponder
	{
		public function SetCurrentUserIdCommand()
		{
		}

		override public function execute(event:CairngormEvent):void
		{
			ConnectModel.getInstance().addQueue("SetCurrentUserIdCommand.execute");
			this.nextEvent = ChainEvent(event).nextChainedEvent;
			
			var delegate : PrincipalListDelegate = new PrincipalListDelegate(this);
			var le : PrincipalListEvent = PrincipalListEvent(event);
			delegate.findUserByLogin(ConnectModel.getInstance().currentUser.nickname);
			
			
		}
		
		public function result(event : Object):void
		{
			// response XML
			ConnectModel.getInstance().addQueue("SetCurrentUserIdCommand.result");
			
			ConnectModel.getInstance().isLogged = true;
			ConnectModel.getInstance().httpServiceHandler = new HttpServiceHandler();
			ConnectModel.getInstance().httpServiceHandler.setXML(event.result);
			
			
			// verify status response
			if (ConnectModel.getInstance().httpServiceHandler.getResultStatus() == ConnectModel.SESSION_OK) {
				if(ConnectModel.getInstance().httpServiceHandler.xml.elements("principal-list").length() > 0){
				    ConnectModel.getInstance().currentUser.account_id = ConnectModel.getInstance().httpServiceHandler.getPrincipalId();    
				} else {
					CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.USER_EXISTS, false, ResponseEvent.OK, event.result));
				}
				this.executeNextCommand();
			} else {
			    CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.INVALID, event.result));
			}
			
			
			
		    
			
		}
		
		public function fault(event : Object):void
		{
			CairngormEventDispatcher.getInstance().dispatchEvent(new ResponseEvent(ResponseEvent.ERROR, false, ResponseEvent.LOGIN_COMMAND_FAULT, event));
			ConnectModel.getInstance().addQueue("LoginCommand.fault");
		}
		
	}
}